// Copyright (c) 1996-2002 John Lyon-Smith. All rights reserved.

#pragma once

#include <wxtl\File.h>

namespace wxtl
{
	class TextFile
	{
	public:
		TextFile()
		{
		}
		~TextFile()
		{
			m_file.close();
		}

		enum
		{
			// For open
			fileRead = 1,
			fileWrite = 2,
			fileShareRead = 4,		// Allow others to read the file
			fileShareWrite = 8,		// Allow others to write to the file
		};

		bool isValid() { return m_file.isValid(); }
		void open(const TCHAR *fileName, unsigned flags = fileRead | fileShareRead) throw(...)
		{
			m_file.open(fileName, flags);
		}
		void close()
		{
			m_file.close();
		}
		
		//
		// Read an ASCII line
		//
		bool readLine(char *p, DWORD dwMax, DWORD& dwActual)
		{
			char ch;
			
			for (dwActual = 0; dwActual != dwMax; dwActual++)
			{
				size_t actual;
			
				if (!m_file.read(p, sizeof(char), &actual) || actual == 0)
					break;
								
				if (*p == '\r')
				{
					if (!m_file.read(&ch, sizeof(char)))
						break;
					
					if (ch == '\n')
					{
						break;
					}
					else
					{
						dwActual++;

						if (dwActual == dwMax)
						{
							break;
						}

						p++;
						*p = ch;
					}
				}

				p++;
			}

			if (dwActual == 0)
				return false;

			*p = 0;
			return true;
		}

	protected:
		File m_file;
	};
}

